<template>
  <div class="greenTheme common_page">
    <!-- 页面头部 -->
    <slot name="top"></slot>
    <ElPageHeader class="p-b-15" v-if="tableConfig.showBack" :icon="ArrowLeft" @back="router.back()">
      <template #content> {{ tableConfig.showBackTitle }} </template>
    </ElPageHeader>
    <!-- 搜索 -->
    <HwitaSearch :tableConfig="tableConfig" @getList="getTableData()" @reset="resetTableData()"><template #search><slot name="otherSearch"/></template></HwitaSearch>
    <!-- 按钮区域 -->
    <HwitaButtons :tableConfig="tableConfig" @refresh="getTableData()"/>
    <!-- 列表区域 -->
    <HwitaTable :tableConfig="tableConfig" :loading="loading" @onCurrentChange="currentChange" @onSizeChange="sizeChange" @onSelect="tabSelect" @onCellClick="onCellClick">
      <template #option="{ row }">
        <slot name="option" :row="row"></slot>
      </template>
    </HwitaTable>
  </div>

</template>
<script setup>
import HwitaSearch from './hwitaSearch.vue'
import HwitaButtons from './hwitaButtons.vue'
import HwitaTable from './hwitaTable.vue'
import { onMounted, reactive, ref, defineExpose, computed, watch } from 'vue'
import columnEumns from './columnEnums'
import {getList} from '@/server/manage/dataProvider.js'
import {getUserList, getRoles} from '@/server/manage/sys.js'
import {getFundList, getProductcategoryList, getProductList} from '@/server/manage/product.js'
import {getChannelList, getAgreementList, getChannelproducList} from '@/server/manage/channel.js'
import {getOrderList, getOrderauthorizationList} from "@/server/manage/incoming"
import { ElPageHeader } from 'element-plus'
import { useRouter } from "vue-router";
import {ArrowLeft} from '@element-plus/icons-vue'

const router = useRouter()
const prop = defineProps(['formKey', 'tableConfig'])
const emit = defineEmits(['onCellClick'])
const loading = ref(false)
// 接口集合 后期只有一个接口 根据formKey返回不同数据
let tabApis = {
  "dataCoverage": getList,
  "dataProviderList": getList,
  "dataMerchantCall": getList,
  "interfaceCall": getList,
  "funderManage": getFundList,
  "productClass": getProductcategoryList,
  "productManage": getProductList,
  "channelInfo": getChannelList,
  "authorizationAgreement": getAgreementList,
  "channelProduct": getChannelproducList,
  "incomingOrdersList": getOrderList,
  "dataAuthorization": getOrderauthorizationList,
  "loanAcceptance": getOrderList,
  "user": getUserList,
  "role": getRoles,
  "sys_menu": getChannelList
}
// 配置集合
const tableConfig = reactive({
  span: 8,
  labelWidth: 100,
  clearable: true,  // 删选可清除
  showIndex: true,  // 是否显示序号
  showSelection: true, // 是否显示选择框
  multiple: true, // 是否可以多选
  operationWidth: 100, // 操作栏宽度
  showPreview: true, // 是否隐藏预览按钮
  showOperation: true, // 是否显示操作栏
  showRefresh: true, // 刷新功能
  showFilter: true, // 筛选显示表头
  showBack: false, // 显示返回按钮
  formItems: [], // 过滤条件组件
  formData: {}, // 过滤条件结果
  buttons: [],  // 按钮数据源
  options: [], // 操作栏
  columns: columnEumns[prop.formKey] || [],  // 表头数据源
  tableData: [], // 表格数据源
  rowData: [], // 被选择行数据
  stripe: true, // 斑马纹
  border: true, // 表格边框
  pagination: {
    pageIndex: 1,
    page: "1",
    pageSize: 10,
    limit: "10",
  },
  total: 0,
})
// 监听
watch(prop.tableConfig, (newVal) => {
  Object.assign(tableConfig, prop.tableConfig)
})
// 递归树
const getTree = (list) => {
  return list.map(item => {
    return {label: item.orgName, value: item.orgName, children: item.subList ? getTree(item.subList):[]}
  })
}
// 搜索框数据
const getFilterData = async() => {
    let rows = []
    tableConfig.formItems = rows.map((field) => {
      let obj = {
          label: field?.fieldHeader,
          prop: field?.fieldName,
          type: field?.elementCode,
          options: field?.optionsList,
          show: true,
        }
      if(field?.fieldName === 'org_name') {
        obj.type = 'tree-select'
        obj.options = getTree(list||[])
      }
      return obj
    })
  }
// 整理搜索参数
const useConvertParams = (tableState) => {
  if (tableState.formItems.length == 0) return []
  if (Object.keys(tableState.formData).length == 0) return []
  let formParams = tableState.formItems?.reduce((acc, cur) => {
    if (tableState.formData[cur.prop]) {
      acc[cur.prop] = tableState.formData[cur.prop]
    }
    return acc
  }, {})
  return formParams
}
// 获取列表数据
const getTableData = async() => {
  loading.value = true
  let params = {
    ...tableConfig.pagination, 
    ...useConvertParams(tableConfig),
    ...tableConfig.otherParams
  }
  for(let key in params) {
    if(tableConfig.formData[key] !== undefined) params[key] = tableConfig.formData[key] // 搜索条件大于传参
  }
  let res = await tabApis[prop.formKey](params)
  tableConfig.total = res?.page?.totalCount||0
  tableConfig.tableData = res?.page?.list||[]
  loading.value = false
  tableConfig.rowData = []
}
// 重置
const resetTableData = () => {
  tableConfig.pagination.pageIndex = 1
  tableConfig.pagination.page = "1"
  getTableData()
}
// 翻页
const currentChange = (page) => {
  tableConfig.pagination.pageIndex = page
  tableConfig.pagination.page = page+''
  getTableData()// 获取列表数据
}
// 选中列
const tabSelect = (list) => {
  tableConfig.rowData = list
}
// 修改一页多少条
const sizeChange = (size) => {
  tableConfig.pagination.pageIndex = 1
  tableConfig.pagination.page = "1"
  tableConfig.pagination.pageSize = size
  tableConfig.pagination.limit = size+''
  getTableData()// 获取列表数据
}
// 当某个单元格被点击时会触发该事件
const onCellClick = (row, column, cell, event) => emit('onCellClick', row, column, cell, event)
onMounted(() => {
  Object.assign(tableConfig, prop.tableConfig)
//   getFilterData()// 获取搜索组件数据
  getTableData()// 获取列表数据 Data coverage
})
defineExpose({tableConfig, getTableData, resetTableData})
</script>
<style scoped>
.common_page{
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--el-color-white);
}
</style>